/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package com.crmapi.controller;



import com.crmapi.group.Save;
import com.crmapi.group.Update;
import com.crmapi.pojo.PageBean;
import com.crmapi.pojo.Result;
import com.crmapi.pojo.User;
import com.crmapi.service.UserService;
import com.crmapi.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.crmapi.pojo.Result.success;

/**
 * <p>Project: CRMSystem - UserController</p>
 * <p>Powered by yzc On 2023-11-15 16:00:12</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
@Slf4j
@Api(tags = "用户管理")
@RestController
@RequestMapping("/api_v1.0")
public class UserController extends BaseController {
    @Autowired
    UserService userService;

   @GetMapping("/user/hello")
   public Result hello(){
       //使用log日志输出
       log.info("欢迎使用CRM客户关系管理系统");
       return success("欢迎使用CRM客户关系管理系统");
   }

   //用户登录
   @PostMapping("/user/login")
   public Result userLogin(String username,String password ){
       User user = userService.userLogin(username);
       if (user == null){
           return Result.error("账号不存在");
       }
       if (username == null || username.equals("")){
           return Result.error("用户名为空");
       }
       if (password == null || password.equals("")){
           return Result.error("密码不能为空");
       }
       //将前端传来的密码使用MD5加密
       String encodePwd = DigestUtils.md5DigestAsHex(password.getBytes());

       log.info("user值为：",user);
       if (!encodePwd.equals(user.getPassword())  ){
           return Result.error("账号或密码不正确");
       }
       String token = TokenUtils.getToken(user.getId(),username);
       Map map = new HashMap<>();
       map.put("user",user);
       map.put("token",token);
       return Result.success(map);
   }

   //修改密码
   @PutMapping("/user/updatePassword")
   public  Result updatePassword(String id ,String oldword ,String password,String repsword){
       if (oldword !=null && oldword != ""){
           if (password.equals(repsword)){
               int rs =  userService.updatePassword(id, password);
               if (rs != 1)
                   return Result.error("修改密码失败");
               return Result.success("修改密码成功");
           }else {
            return Result.error("两次密码不一致");
           }
       }else {
           return Result.error("请提供旧密码");
       }
   }

   @ApiOperation("查询用户")
   @ApiImplicitParams({
           @ApiImplicitParam(name ="page",value = "当前页",required = true),
           @ApiImplicitParam(name = "pageSize",value = "每页最多几条数据",required = true),
           @ApiImplicitParam(name = "name",value = "员工名称",required = true),
           @ApiImplicitParam(name = "deptName",value = "部门名称",required = true),
           @ApiImplicitParam(name = "jobName",value = "岗位名称",required = true)
   })
   @PostMapping  ("/user/list")
   public Result queryUser(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer pageSize,
                           String name, String deptName ,String jobName,Integer status){
       log.info("分页条件参数{},{},{},{},{},{}",page,pageSize,name,deptName,jobName,status);
       PageBean pageBean = userService.queryUser(page,pageSize,name,deptName,jobName,status);
       return success(pageBean );
   }

    @ApiOperation("保存用户")
    @PostMapping("/user/save")
    public Result save(@Validated(value = {Save.class})@RequestBody User user , BindingResult result){
        validator(result);
        int i = userService.queryUsername(user.getUsername());
        log.info("i：{}",i);
        if (i ==0 ){
            int rs=userService.save(user);
            if (rs!=1)
                return Result.error("保存失败");
            return Result.success("保存成功");
        }else {
            return Result.error("已存在该用户名");
        }



    }

    @ApiOperation("批量删除")
    @ApiImplicitParam(name = "ids",value = "用户id",required = true)
    @DeleteMapping("/user/del/{ids}")
    public Result delete(@PathVariable List<String> ids){
       log.info("批量删除操作,ids:{}",ids);
        int rs =userService.delByIds(ids);
        if (rs == 0)
            return Result.error("删除失败");
       return Result.success("删除成功");
    }

    @ApiOperation("更新用户")
    @PutMapping("/user/update")
    public Result update(@Validated(Update.class)@RequestBody User user, BindingResult result){
       validator(result);
        int rs= userService.update(user);
        if (rs==0)
           return Result.error("更新失败");
        return Result.success("更新成功");
    }
}
